package com.mysiteforme.admin.controller.question;

import com.mysiteforme.admin.entity.question.ChChoice;
import com.mysiteforme.admin.entity.question.ChQuestion;
import com.mysiteforme.admin.entity.question.ChQuestionVO;
import com.mysiteforme.admin.entity.question.QuestionSolr;
import com.mysiteforme.admin.realm.AuthRealm;
import com.mysiteforme.admin.service.question.ChChoiceService;
import com.mysiteforme.admin.service.question.ChQuestionService;
import com.mysiteforme.admin.util.*;
import com.xiaoleilu.hutool.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.zookeeper.data.Id;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yj
 * @since 2019-04-24
 */
@Controller
@RequestMapping("/chQuestion")
@Slf4j
public class ChQuestionController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChQuestionController.class);

    @Resource
    private SolrClient httpSolrClient;

    @Autowired
    private ChQuestionService chQuestionService;

    @Resource
    private QiNiuGetExamToken qiNiuGetExamToken;

    @Resource
    private ChChoiceService chChoiceService;

    @GetMapping("list")
    @SysLog("跳转列表")
    public String list() {
        return "/ytzlquestion/chQuestion/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求列表数据")
    public LayerData<ChQuestion> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                      ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "");
        LayerData<ChQuestion> layerData = new LayerData<>();
        EntityWrapper<ChQuestion> wrapper = new EntityWrapper<>();
        if (!map.isEmpty()) {
            wrapper.eq("del_flag", 1);
            if (map.get("searchInfo") != null || map.get("searchInfo") != "") {
                wrapper.like("key_words", (String) map.get("searchInfo"));
            }
            if (map.get("lorePointId") != null && map.get("lorePointId") != "") {
                wrapper.eq("lore_point_id", (String) map.get("lorePointId"));
            }
            if (map.get("questionType") != null && map.get("questionType") != "") {
                wrapper.eq("question_type", (String) map.get("questionType"));
            }
        }
        Page<ChQuestion> pageData = chQuestionService.selectPage(new Page<>(page, limit), wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @PostMapping("questionVOlist")
    @ResponseBody
    @SysLog("请求solr查询questionVO")
    public LayerData<ChQuestionVO> questionVOlist(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                                  @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                                  ServletRequest request) throws IOException, SolrServerException {
        LayerData<ChQuestionVO> layerData = new LayerData<>();
//        Page<ChQuestionVO> pageData = new Page<>(page, limit);
        Map map = WebUtils.getParametersStartingWith(request, "");
        EntityWrapper<ChQuestion> wrapper = new EntityWrapper<>();

        //随机查询测试题 条件 符合知识点Id列表
        SolrQuery solrQuery = new SolrQuery("*:*");
        solrQuery.addFilterQuery("delFlag:"+1);
        if (map.get("searchInfo") != null && map.get("searchInfo") != ""){
            solrQuery.addFilterQuery("keywords:*"+(String)map.get("searchInfo")+"*");
        }
        // 起始页
        solrQuery.setStart((page-1)*limit);
        // 每页显示数量
        solrQuery.setRows(limit);
        List<ChQuestionVO> chQuestionVOList = new ArrayList<>();
        QueryResponse queryResponse = httpSolrClient.query("question",solrQuery);
        List<QuestionSolr> questionSolrList = queryResponse.getBeans(QuestionSolr.class);
        if (questionSolrList == null || questionSolrList.size()==0){
            LOGGER.info("solr获取题目列表为空----------------------------------------");
        }
        for (int i = 0;i<questionSolrList.size();i++){

            ChQuestionVO chQuestionVO = new ChQuestionVO();
            List<String> choiceList = questionSolrList.get(i).getChoiceList();
            if(choiceList!=null && choiceList.size()>0){
                if(choiceList.get(0)!=null&&choiceList.get(0)!="") {
                    chQuestionVO.setAnwser1(choiceList.get(0).split("@")[1]);
                    chQuestionVO.setA1ok(choiceList.get(0).split("@")[2]);
                }
                else
                    chQuestionVO.setAnwser1("无答案");
                if(choiceList.get(1)!=null&&choiceList.get(1)!="") {
                    chQuestionVO.setAnwser2(choiceList.get(1).split("@")[1]);
                    chQuestionVO.setA2ok(choiceList.get(1).split("@")[2]);
                }
                else
                    chQuestionVO.setAnwser2("无答案");
                if(choiceList.get(2)!=null&&choiceList.get(2)!="") {
                    chQuestionVO.setAnwser3(choiceList.get(2).split("@")[1]);
                    chQuestionVO.setA3ok(choiceList.get(2).split("@")[2]);
                }
                else
                    chQuestionVO.setAnwser3("无答案");
                if(choiceList.get(3)!=null&&choiceList.get(3)!="") {
                    chQuestionVO.setAnwser4(choiceList.get(3).split("@")[1]);
                    chQuestionVO.setA4ok(choiceList.get(3).split("@")[2]);
                }
                else
                    chQuestionVO.setAnwser4("无答案");

            }else{
                chQuestionVO.setAnwser1("无答案");
                chQuestionVO.setAnwser2("无答案");
                chQuestionVO.setAnwser3("无答案");
                chQuestionVO.setAnwser4("无答案");
            }
            BeanUtils.copyProperties(questionSolrList.get(i),chQuestionVO);
            chQuestionVOList.add(chQuestionVO);
        }
        layerData.setData(chQuestionVOList);
        layerData.setCount((int) queryResponse.getResults().getNumFound());
        return layerData;
    }




    @GetMapping("add")
    @SysLog("跳转新增页面")
    public String add() {
        return "/ytzlquestion/chQuestion/add";
    }

    @PostMapping("add")
    @SysLog("保存新增数据")
    @ResponseBody
    public RestResponse add(ChQuestionVO chQuestionVO) {
        chQuestionVO.setId(IdWorker.getId());
        chQuestionVO.setCreationBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        chQuestionVO.setCreationDate(new Date());
        ChQuestion chQuestion = new ChQuestion();
        BeanUtils.copyProperties(chQuestionVO,chQuestion);
        boolean add = chQuestionService.insertQuestion(chQuestion);
        if (add) return RestResponse.success();
        else return RestResponse.failure("系统繁忙");
    }

    @GetMapping("getType")
    @SysLog("获取题目类型")
    @ResponseBody
    public RestResponse getType(@RequestParam("questionId") String questionId) {
        if (questionId == "" || questionId == null) {
            return RestResponse.failure("题目ID为空！！！");
        }
        String res = chQuestionService.getType(questionId);
        return RestResponse.success().setData(res);
    }

    @GetMapping("edit")
    @SysLog("跳转编辑页面")
    public String edit(Long id, Model model) {
        ChQuestion chQuestion = chQuestionService.selectById(id);
        model.addAttribute("chQuestion", chQuestion);
        return "/ytzlquestion/chQuestion/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑数据")
    public RestResponse edit(ChQuestion chQuestion) {
        if (null == chQuestion.getId() || "" == chQuestion.getId()) {
            return RestResponse.failure("ID不能为空");
        }
        chQuestion.setModifyedDate(new Date());
        chQuestion.setModifyedBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        boolean update = chQuestionService.updateQuestoinById(chQuestion);
        if (update) return RestResponse.success();
        else return RestResponse.failure("系统繁忙");
    }

    @PostMapping("deleteAll")
    @ResponseBody
    @SysLog("批量删除数据")
    public RestResponse deleteAll(@RequestParam(value = "ids") String ids) {
        if (null == ids || "" == ids) {
            return RestResponse.failure("ID不能为空");
        }
        ids = "(" + ids + ")";
        boolean del = chQuestionService.deleteQuestionByIds(ids);
        if (del) return RestResponse.success();
        else return RestResponse.failure("系统繁忙");
    }

    @PostMapping("delete")
    @ResponseBody
    @SysLog("刪除单个数据")
    public RestResponse delete(@RequestParam(value = "id") String id) {
        if (null == id || "" == id) {
            return RestResponse.failure("ID不能为空");
        }
        boolean del = chQuestionService.deleteQuestionById(id);
        if (del) return RestResponse.success();
        else return RestResponse.failure("系统繁忙");
    }

    @GetMapping("creatExam")
    @SysLog("跳转出题页面")
    public String creatExam() {
        return "/ytzlquestion/chQuestion/creatExam";
    }

    @PostMapping("creatQandA")
    @ResponseBody
    @SysLog("保存编辑数据")
    public RestResponse creatQandA(ChQuestionVO chQuestionVO) {
        chQuestionVO.setId(IdWorker.getId());
        chQuestionVO.setCreationDate(new Date());
        chQuestionVO.setCreationBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        boolean update = chQuestionService.creatQandA(chQuestionVO);
        if (update) return RestResponse.success();
        else return RestResponse.failure("系统繁忙");
    }


}